#include "StdAfx.h"
#include "gamebutton.h"

const int pixmapWidth = 64;
const int pixmapHeight = 64;
const int buttonWidth = 312;
const int buttonHeight = 64;

GameButton::GameButton(const QString& fileName, const QString& buttonString, QGraphicsItem *parent )
   : QGraphicsObject(parent)
   , m_pixmap(fileName)
   , m_pressed(false)
   , m_font("Times", 24, QFont::Bold)
   , m_fontColor(255,255,255)
   , m_buttonString(buttonString)
   , m_hovered(false)
{
   init();
}

GameButton::~GameButton()
{

}

void GameButton::init()
{
   m_fontPen = boost::make_shared<QPen>(m_fontColor);
   setAcceptHoverEvents(true);
   setFlag(ItemIsSelectable);
   translate(-pixmapWidth / 2, -pixmapHeight / 2);
   m_pixmap = m_pixmap.scaled(pixmapWidth, pixmapHeight);
}

void GameButton::mousePressEvent( QGraphicsSceneMouseEvent *event )
{
   qDebug() << "GameButton::mousePressEvent";
   QGraphicsItem::mousePressEvent(event);
   m_pressed = true;
}

void GameButton::mouseReleaseEvent( QGraphicsSceneMouseEvent *event )
{
   qDebug() << "GameButton::mouseReleaseEvent";
   QGraphicsItem::mouseReleaseEvent(event);
   if (m_pressed)
   {
      m_pressed = false;
      emit clicked();
   }
}

void GameButton::paint( QPainter *painter, const QStyleOptionGraphicsItem *, QWidget * /* = 0 */ )
{
   painter->drawPixmap(0, 0, m_pixmap);
   if (m_hovered)
   {
      painter->setFont(m_font);
      painter->setPen(*m_fontPen);
      painter->drawText(boundingRect(), Qt::AlignCenter, m_buttonString);
   }
}

QRectF GameButton::boundingRect() const
{
   return QRectF(0, 0, buttonWidth, buttonHeight);
}

void GameButton::hoverEnterEvent( QGraphicsSceneHoverEvent *event )
{
   QGraphicsItem::hoverEnterEvent(event);
   m_hovered = true;
}

void GameButton::hoverLeaveEvent( QGraphicsSceneHoverEvent *event )
{
   QGraphicsItem::hoverLeaveEvent(event);
   m_hovered = false;
}